let http = require("http");
let fs = require("fs");
let nunjucks = require("nunjucks");
let server = http.createServer();

let session = [];

server.listen(8080);
server.on('request', function (req, res) {
    let postData = '';
    req.on('data', function (chunk) {    //流方式读取数据，数据是一段一段传输的,异步
        postData += chunk;
    })

    req.on('end', async function () {    //流接受完毕
        console.log('流方式获取到的数据:');
        console.log(postData);      //获取到username,password和repeatpsd

        //拆分post请求的数据步骤
        let postArr = postData.split("&");
        let postVals = [];
        for (let ky in postArr) {
            let val = postArr[ky];
            let temPostArray = val.split("=");
            postVals[temPostArray[0]] = temPostArray[1];
        }
        req.post = postVals;

        let url = req.url;
        // console.log('网页url:' + url);
        //判断静态资源
        if (url.lastIndexOf('.') > -1) {
            console.log('网页url:' + url);
            let path = '.' + url;
            readFileByPromise(path, res);
        } else {
                //获取cookie,将cookie转化成key，value形式

            if(req.headers.cookie) {
                let cookieStrArr = req.headers.cookie.split(';');
                let cookies = {};
                cookieStrArr.forEach(element => {
                    let cookieKeyAndVal = element.split("=");
                    cookies[cookieKeyAndVal[0]] = cookieKeyAndVal[1];
                });
                req.cookie = cookies;
            }
            // console.log(req.cookie);
            let node_session = null;
            if(!req.cookie.node_session) {  
                node_session = (new Date().getTime()+"_"+Math.random());
                res.setHeader('Set-Cookie',"node_session="+node_session);
                req.cookie.node_session = node_session;
            } else {
                 node_session = req.cookie.node_session;
            }

            //判断动态资源，以demo?a=index&c=index为例
            res.setHeader("Content-type", "text/html;charset=utf8");
            //根据cookie获取session的值
            if(session[node_session]) {
                console.log('session data');
                console.log(session);
                req.session = session[node_session];
            }
            //去除query
            let queryString = url.split("?")[1]; //取'?' 后的数据
            console.log(queryString);   //打印a=index&c=index
            let queryArr = queryString.split('&');  //打印['a=index','c=index'];
            console.log(queryArr);
            let keyVals = [];   //创建一个空数组
            for (let key in queryArr) {  //让key在 queryArr 中遍历
                let vals = queryArr[key];
                // console.log('vals:' +vals); //1.  a=index 2.  c=index
                let temArray = vals.split("=");
                // console.log('temArray:'+temArray);  //1.  a,index   2. c,index
                keyVals[temArray[0]] = temArray[1];  //让a=index c=index
            }
            req.query = keyVals;    //base.js敲完后加(给对象添加一个query)
            console.log(keyVals['c']);
            let controllerPath = './home/controller/' + keyVals['c'].replace(keyVals[0], keyVals['c'][0].toUpperCase()) + "Controller";
            //正常的项目.controller 是由多个的，model也是有多个的,所以通过url 可动态的调用
            let controller = require(controllerPath);   //controller 就是一个class
            //这时候controllerPath 获取到home/controller/index.js 文件,进行调用
            // console.log(keyVals['a']); //打印index
            //keyVals['a'] 变量,所以在json 里面，要去调用它的key ,用 .方式 key必须是个常量,
            let action = keyVals['a'];
            let obj = new controller(req, res, nunjucks);   //找控制器，然后执行控制器下的方法
            let content = await obj[action]();
            if(this.session) {
                session[node_session] = res.session;
            } 
            if(content == '301') {
                res.writeHead({'location':'/?c=user&a=userList'});
                res.end();
            } else {
                res.write(content);
                res.end();
            }
            // res.setHeader('Set-Cookie',['demo=12345','demo2=678910']);
            // let date = new Date();
            // date.setTime(date.getTime() + 30 * 60 * 10000);
            // console.log(date);    //2022-03-23T02:18:37.797Z
            // res.setHeader('Set-Cookie', "userInfo=987654321; expires="+date.toGMTString()+"; path=/mydir;");
            // res.write(content);
            // res.end();
            // console.log(controller[show](req,res));  //json 访问,如果key是变量要在[]
        }
    })

})

let promise = function (filename) {
    return new Promise(function (resolve, reject) {
        fs.exists(filename, function (result) {
            if (!result) {
                filename = './home/imgs/404.png';
            }
            fs.readFile(filename, function (err, data) {
                resolve(data);
            })
        })
    })
}

async function readFileByPromise(fileName, res) {
    let data = await promise(fileName);
    if (data) {
        res.write(data);
    }
    res.end();
}


